import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.css'
import '@/common/comm.css'
import axios from './utils/axios'
import {generateIndexRouter} from "@/utils/util"

Vue.config.productionTip = false
Vue.prototype.$axios = axios

router.beforeEach((to, from, next) => {
  if (!store.state.UserToken) {
    if (to.matched.length > 0 && !to.matched.some(record => record.meta.requiresAuth)) {
      next({path:'/index'})
    } else {
      next({ path: '/login' })
    }
  } else {
    if (!store.state.permission.permissionList) {
      store.dispatch('GetPermissionList').then(res => {
        const menuData = res.menu
        if (menuData === null || menuData === "" || menuData === undefined) {
          return;
        }
        let constRoutes = [];
        constRoutes = generateIndexRouter(menuData);
        // 添加主界面路由
        store.dispatch('permission/UpdateAppRouter',{constRoutes}).then(()=>{
           // 根据roles权限生成可访问的路由表
            // 动态添加可访问路由表
            router.selfaddRoutes(store.getters.addRouters)
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            if(to.path === redirect){
              // next({...to, replace: true})
              next()
            }else{
              // 跳转到目的路由
              next({path: redirect})
            }

        })
      }).catch(()=>{
        //退出
      })

      // store.dispatch('permission/FETCH_PERMISSION').then(() => {
      //   next({ path: to.path })
      // })
    
    } else {
      if (to.path !== '/login') {
        next()
      } else {
        next(from.fullPath)
      }
    }
  }
})

Vue.use(Antd)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
